import {
  ActivityIndicator,
  FlatList,
  RefreshControl,
  StyleSheet,
  View,
} from "react-native";
import { CartoonScreenProps } from "../../types/NavigationTypes";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import apiService from "../../services/ApiServices";

import CartoonCardView from "../../components/CartoonCardView";
import { __isEmpty } from "../../common/utils";
import CartoonSearchView, { CartoonSearchViewRef } from "../../components/CartoonSearchView";
import LottieView from "lottie-react-native";

const CartoonScreen: React.FC<CartoonScreenProps> = ({ navigation, route }) => {
  const [viewHeight, setViewHeight] = useState(0);

  const [cartoonList, setCartoonList] = useState<any[]>([]);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [rcmdCartoonList, setRcmdCartoonList] = useState<any[]>([]);

  const currentIndex = useRef(0);
  const tabIdRef = useRef("");
  const pageRef = useRef(1);
  const searchViewRef = useRef<CartoonSearchViewRef>(null);
  
  useLayoutEffect(() => {
    navigation.setOptions({
      headerTitle: () => <CartoonSearchView cartoonList={rcmdCartoonList.slice(0, 3)} ref={searchViewRef}/>,
      headerTitleAlign: "left",
    });
  }, [navigation, rcmdCartoonList]);

  useEffect(() => {
    fetchRecommendCartoons();
    fetchData();
  }, []);

  const fetchRecommendCartoons = async () => {
    const result = await apiService.getRecommendCartoons();
    setRcmdCartoonList(result?.data);
  };

  const fetchData = async () => {
    if (__isEmpty(tabIdRef.current)) {
      const id = await fetchTabId();
      tabIdRef.current = id;
    }
    const data = await fetchCartoonList(tabIdRef.current, pageRef.current);
    if (data.list.length === 0) {
      setIsRefreshing(false);
      return;
    }
    if (pageRef.current === 1) {
      setCartoonList(data.list);
    } else {
      setCartoonList((prev) => [...prev, ...data.list]);
    }
    setIsRefreshing(false);
    setIsLoading(false);
  };

  const fetchTabId = async (): Promise<string> => {
    const result = await apiService.getCartoonTabId();
    return result?.data[0].id;
  };

  const fetchCartoonList = async (
    tabId: string,
    page: number
  ): Promise<any> => {
    console.log("🤣 fetching data page: " + page);
    const result = await apiService.getCartoonList(tabId, page);
    return result?.data;
  };

  const loadMore = () => {
    pageRef.current += 1;
    fetchData();
  };

  const onRefresh = () => {
    setIsRefreshing(true);
    pageRef.current = 1;
    fetchData();
  };

  return (
    <View
      style={styles.container}
      onLayout={(event) => {
        const { height } = event.nativeEvent.layout;
        setViewHeight(height);
      }}
    >
      {isLoading ? (
        <View
          style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
        >
          <LottieView
            source={require("../../../assets/animations/loading.json")}
            style={{ width: 100, height: 100 }}
            autoPlay
            loop
          />
        </View>
      ) : (
        <FlatList
          data={cartoonList}
          horizontal={false}
          pagingEnabled={true}
          showsVerticalScrollIndicator={true}
          renderItem={({ item, index }) => (
            <CartoonCardView index={index} rcmdCartoonList={rcmdCartoonList} item={item} viewHeight={viewHeight} />
          )}
          keyExtractor={(item) => item.id}
          onEndReached={loadMore}
          onEndReachedThreshold={0.2}
          onMomentumScrollEnd={(e) => {
            const index = Math.round(e.nativeEvent.contentOffset.y / e.nativeEvent.layoutMeasurement.height);
            if (index !== currentIndex.current) {
             
              console.log(`当前index：${index}`);
       
              if (index == 0 && currentIndex.current == 1) {
                searchViewRef.current?.playAnimation();
              }
              if (index == 1 && currentIndex.current == 0) {
                searchViewRef.current?.playAnimation();
              }

              currentIndex.current = index;
            }
          
          }}
          refreshControl={
            <RefreshControl refreshing={isRefreshing} onRefresh={onRefresh} />
          }
          
        />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "white" },
});

export default CartoonScreen;
